#!/bin/bash

MODE=$1
shift
while getopts "h?d:i:p:n:r" opt; do
  case "$opt" in
  h | \?)
    printHelp
    exit 0
    ;;
  d)
    DIR=$OPTARG
    ;;
  i)
    IP=$OPTARG
    ;;
  p)
    PASSWORD=$OPTARG
    ;;
  n)
    NAME=$OPTARG
    ;;
  r)
    REMOVE_FLAG=true
    ;;
  esac
done

LOCAL_IP=`ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v 172.|grep -v 10.|grep -v inet6|awk '{print $2}'|tr -d "addr:"`

function joinToken() {

  if [ "${REMOVE_FLAG}" == "true" ]; then
    # maybe recreate token 
    kubeadm token create
  fi

  # combined kubeadm join command
  kubeadm token list > kube.join
  token=`grep "authentication,signing" kube.join |awk '{print $1}'`
  if [[ -z "${token}" ]]; then
    echo "token expired,run 'cmd.sh jointoken -r' to generate it again."
    exit 0
  fi
  
  rm -rf ./kube.join
  cahash=`openssl x509 -pubkey -in /etc/kubernetes/pki/ca.crt | openssl rsa -pubin -outform der 2>/dev/null | openssl dgst -sha256 -hex | sed 's/^.* //'`
  ip=$LOCAL_IP
  kubejoin='kubeadm join '$ip':6443 --token '$token' --discovery-token-ca-cert-hash sha256:'$cahash

  echo $kubejoin

  echo '手动复制以上命令，在要加入集群的node节点中运行'
}

function remove(){
  if [[ -n "${NAME}" ]]; then
    kubectl cordon $NAME
    kubectl drain $NAME --delete-emptydir-data --force --ignore-daemonsets
    kubectl delete node $NAME

    # in slave run following cammand
    # kubeadm reset && ifconfig cni0 down && ip link delete cni0
  fi
}

function nfs () {
  
  if [ "${REMOVE_FLAG}" == "true" ]; then
    (
      cd ./nfs
      bash master_nfs.sh delete
    )
    exit 0
  fi
  
  (
    cd ./nfs
    bash master_nfs.sh
  )
}

function glusterfs() {
  if [ "${REMOVE_FLAG}" == "true" ]; then
    kubectl delete -f ./vm/vm1.yaml -f ./vm/vm1-pvc.yaml
    kubectl delete -f ./vm/sc-glusterfs.yaml
    exit 0
  fi
  
  CLUSTERIP=`kubectl get svc -n glusterfs|grep NodePort|awk '{print $3}'`
  echo $CLUSTERIP
  sed -i 's/127.0.0.1/'$CLUSTERIP'/g' ./vm/sc-glusterfs.yaml
  
  kubectl apply -f ./vm/sc-glusterfs.yaml

  if [ "$2" == "vm1" ]; then
    kubectl apply -f ./vm/vm1.yaml -f ./vm/vm1-pvc.yaml
  fi

}

function vmTest() {

  dir=$DIR
  if [[ -z "${dir}" ]]; then
    dir="vm1"
  fi

  if [ "${REMOVE_FLAG}" == "true" ]; then
    kubectl delete -f ./vm/$dir
    exit 0
  fi


  kubectl apply -f ./vm/$dir

}

function createCerts(){

  if [ "${REMOVE_FLAG}" == "true" ]; then
    
    rm -rf ca.pem key.pem cert.pem
    rm -rf ./tls-certs
    rm -rf tls-certs.tar.gz tls-client-certs.tar.gz

    exit 0
  fi


  SSH_PASSWORD=$PASSWORD
  if [[ -z "${SSH_PASSWORD}" ]]; then
    SSH_PASSWORD="newlandedu"
  fi
  
  # Generate CA key
  openssl genrsa -aes256 -passout "pass:$SSH_PASSWORD" -out "ca-key.pem" 4096
  # Generate CA
  openssl req -new -x509 -days 1825 -key "ca-key.pem" -sha256 -out "ca.pem" -passin "pass:$SSH_PASSWORD" -subj "/C=CN/ST=BEIJING/L=BEIJING/O=NEWLANDEDU/OU=DEV/CN=$LOCAL_IP/emailAddress=admin@nlecloud.com"
  # Generate Server key
  openssl genrsa -out "server-key.pem" 4096
  # Generate Server Certs
  openssl req -subj "/CN=$LOCAL_IP" -sha256 -new -key "server-key.pem" -out server.csr
  echo "subjectAltName = IP:$LOCAL_IP,IP:192.168.0.248,IP:0.0.0.0" >> extfile.cnf
  echo "extendedKeyUsage = serverAuth" >> extfile.cnf
  openssl x509 -req -days 1825 -sha256 -in server.csr -passin "pass:$SSH_PASSWORD" -CA "ca.pem" -CAkey "ca-key.pem" -CAcreateserial -out "server-cert.pem" -extfile extfile.cnf
  rm -f extfile.cnf
  # Generate Client Certs
  openssl genrsa -out "key.pem" 4096
  openssl req -subj '/CN=client' -new -key "key.pem" -out client.csr
  echo "extendedKeyUsage = clientAuth" >> extfile.cnf
  openssl x509 -req -days 1825 -sha256 -in client.csr -passin "pass:$SSH_PASSWORD" -CA "ca.pem" -CAkey "ca-key.pem" -CAcreateserial -out "cert.pem" -extfile extfile.cnf
  rm -vf client.csr server.csr
  rm -f extfile.cnf

  # Package certificate
  mkdir -p "tls-certs"
  cp -f ca-key.pem ca.pem server-key.pem server-cert.pem key.pem cert.pem tls-certs/
  cd tls-certs
  tar zcf "tls-certs.tar.gz" *
  mv "tls-certs.tar.gz" ../
  cd ..
  rm -rf "tls-certs"

  # Package client certificate
  mkdir -p "tls-client-certs"
  cp -f ca.pem cert.pem key.pem tls-client-certs/
  cd tls-client-certs
  tar zcf "tls-client-certs.tar.gz" *
  mv "tls-client-certs.tar.gz" ../
  cd ..
  rm -rf "tls-client-certs"

  rm -rf ca.srl ca-key.pem server-key.pem server-cert.pem
  ls
}

function dockerApi(){
  # yum install jq -y
  # cat aa.json |jq '."insecure-registries" + ["127.0.0.1"]' 
  # jq 'del(."insecure-registries")' aa.json

  TLS=false

  if [ "${REMOVE_FLAG}" == "true" ]; then
    sed -i '/unix:\/\/\/var\/run\/docker.sock -H tcp:/d' /lib/systemd/system/docker.service
    sed -i "s/#ExecStart=\/usr\/bin\/dockerd -H fd:/ExecStart=\/usr\/bin\/dockerd -H fd:/g" /lib/systemd/system/docker.service
    
    HARBOR_HOSTNAME='"harbor.rs.nlecloud.com"'
    sed -i "s/\"insecure-registries\"/#\"insecure-registries\"/g" /etc/docker/daemon.json
    sed -i "/#\"insecure-registries\"/a\"insecure-registries\":[$HARBOR_HOSTNAME]" /etc/docker/daemon.json
    sed -i '/#\"insecure-registries\"/d' /etc/docker/daemon.json

    rm -rf /etc/docker/certs.d

    systemctl daemon-reload
    systemctl restart docker
    curl http://$LOCAL_IP:15326/images/json
    exit 0
  fi

  # open docker tls api
  if [[ "${TLS}" == "true" ]]; then

    if [ ! -d "./tls-certs" ]; then
      mkdir -p ./tls-certs && tar zxvf tls-certs.tar.gz -C ./tls-certs
    fi
    
    cd ./tls-certs
    # set cert file permissions
    chmod -v 0400 ca-key.pem server-key.pem key.pem 
    chmod -v 0444 ca.pem server-cert.pem cert.pem

    # Copy server certificate
    mkdir -p /etc/docker/certs.d
    cp ca.pem server-key.pem server-cert.pem /etc/docker/certs.d/
    cd ..

    # enable docker api
    sed -i "s/ExecStart=\/usr\/bin\/dockerd -H fd:/#ExecStart=\/usr\/bin\/dockerd -H fd:/g" /lib/systemd/system/docker.service
    sed -i "/#ExecStart=/aExecStart=\/usr\/bin\/dockerd -H unix:\/\/\/var\/run\/docker.sock -H tcp:\/\/$LOCAL_IP:15326 --tlsverify --tlscacert=/etc/docker/certs.d/ca.pem --tlscert=/etc/docker/certs.d/server-cert.pem --tlskey=/etc/docker/certs.d/server-key.pem" /lib/systemd/system/docker.service
  else
    # enable docker api
    sed -i "s/ExecStart=\/usr\/bin\/dockerd -H fd:/#ExecStart=\/usr\/bin\/dockerd -H fd:/g" /lib/systemd/system/docker.service
    sed -i "/#ExecStart=/aExecStart=\/usr\/bin\/dockerd -H unix:\/\/\/var\/run\/docker.sock -H tcp:\/\/$LOCAL_IP:15326" /lib/systemd/system/docker.service
  fi
  
  
  # docker registry default user https,if set then user http
  HARBOR_HOSTNAME='"harbor.rs.nlecloud.com"'
  echo -n "Enter Your Harbor Address: "
  read harbor_address
  if [[ -n "${harbor_address}" ]]; then
      HARBOR_HOSTNAME=$HARBOR_HOSTNAME',"'$harbor_address'"'
      sed -i "s/\"insecure-registries\"/#\"insecure-registries\"/g" /etc/docker/daemon.json
      sed -i "/#\"insecure-registries\"/a\"insecure-registries\":[$HARBOR_HOSTNAME]" /etc/docker/daemon.json
      sed -i '/#\"insecure-registries\"/d' /etc/docker/daemon.json
  fi

  # restart docker
  systemctl daemon-reload
  systemctl restart docker
  
  # debug
  if [[ "${TLS}" == "true" ]]; then
    echo "docker --tlsverify --tlscacert=./ca.pem --tlscert=./cert.pem --tlskey=./key.pem -H tcp://$LOCAL_IP:15326 images"
    curl -v https://$LOCAL_IP:15326/images/json --cacert ./tls-certs/ca.pem --cert ./tls-certs/cert.pem --key ./tls-certs/key.pem
    #rm -rf ./tls-certs
  else
    curl http://$LOCAL_IP:15326/images/json
  fi
}

function sshWithoutPasswd () {

  OS=`lsb_release -a|grep 'Distributor ID'|awk '{print $3}'`
  if [[ "${OS}" == "CentOS" ]]; then
    yum install -y expect
  else
    apt install -y expect
  fi
  
  rm -rf ~/.ssh
  if [ "${REMOVE_FLAG}" == "true" ]; then
    exit 0
  fi
  
  if [[ -z "${PASSWORD}" ]]; then
    PASSWORD='newlandedu@123'
  fi
  

  ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa &> /dev/null
  for ip in $(echo $IP | sed "s/,/ /g")
  do
      expect <<EOF
      spawn ssh-copy-id -i root@${ip}
      expect {
          "yes/no" 
          { send "yes\n";exp_continue }
          "password" 
          { send "${PASSWORD}\n" }
      }
      expect eof
EOF
  done
  echo 'success'
}


function printHelp() {
  echo "  cmd.sh join/nfs/glusterfs/vmtest/dockerapi [-r] [-n]"
  echo "    -r - anew or recreate or afresh"
  echo "  cmd.sh (print this message)"
  echo
  echo "  1.print z8s join token:"
  echo "    cmd.sh jointoken [-r]"
  echo "  2.remove z8s node:"
  echo "    cmd.sh remove [-n]"
  echo "  3.create or remove nfs:"
  echo "    cmd.sh nfs [-r]"
  echo "  4.create or remove glusterfs:"
  echo "    cmd.sh glusterfs [-r]"
  echo "  5.create vm svc,pod:"
  echo "    cmd.sh vmtest [-d directory] [-r]"
  echo "  6.create or remove ssl cert:"
  echo "    cmd.sh cert [-p sslpasswd] [-r]"
  echo "  7.open or close docker api:"
  echo "    cmd.sh dockerapi [-p sslpasswd] [-r]"
  echo "  8.open or close ssh without:"
  echo "    cmd.sh sshwithout [-i 192.168.0.171 -p newlandedu@123]"
}

if [ "${MODE}" == "jointoken" ]; then
  joinToken
elif [ "${MODE}" == "remove" ]; then
  remove
elif [ "${MODE}" == "nfs" ]; then
  nfs
elif [ "${MODE}" == "glusterfs" ]; then 
  glusterfs
elif [ "${MODE}" == "vmtest" ]; then
  vmTest
elif [ "${MODE}" == "cert" ]; then 
  createCerts
elif [ "${MODE}" == "dockerapi" ]; then 
  dockerApi
elif [ "${MODE}" == "sshwithout" ]; then 
  sshWithoutPasswd
else
  printHelp
  exit 1
fi
